import uCharts from '@/uni_modules/qiun-data-charts/js_sdk/u-charts/config-ucharts.js';
function getLocalFilePath(path) {
	if (path.indexOf('_www') === 0 || path.indexOf('_doc') === 0 || path.indexOf('_documents') === 0 || path.indexOf(
		'_downloads') === 0) {
	  return path
	}
	if (path.indexOf('file://') === 0) {
	  return path
	}
	if (path.indexOf('/storage/emulated/0/') === 0) {
	  return path
	}
	if (path.indexOf('/') === 0) {
	  let localFilePath = plus.io.convertAbsoluteFileSystem(path)
	  if (localFilePath !== path) {
		return localFilePath
	  } else {
		path = path.substr(1)
	  }
	}
	return '_www/' + path
}
const install = Vue => {
	const that = Vue.prototype;
	// 是否显示会员权益模块
	that.showMember = false;

	// 是否显示领取考试大纲按钮
	that.notShowClaimOutLine = true;

	that.baikeLogobaseBg = '';
	Vue.prototype.schoolType = {
		'公办': 'public',
		'公办院校': 'public',
		"公办学院": "public",
		'民办': 'civilian',
		'民办院校': 'civilian',
		"民办学院": "civilian",
		'独立': 'independent',
		'独立院校': 'independent',
		"独立学院": "independent",
		"职业本科": "occupation",
	};

	// 背景图转base64
	Vue.prototype.getBaikeLogobaseBg = async function(){
		let url = await that.pathToBase64('/static/imgs/mask.png');
		that.baikeLogobaseBg = url;
	}
	// 省份列表
	Vue.prototype.provinceList = [];
	// 热门省份列表
	Vue.prototype.hotProvince = [];

	// 快递公司
	Vue.prototype.expressCompany = {
		yuantong: {
			name: "圆通速递",
			img: "https://bicpic.baikewang.com/images/1636616024003.png",
		},
		yunda: {
			name: "韵达快递",
			img: "https://bicpic.baikewang.com/images/1636619630421.png",
		},
		zhongtong: {
			name: "中通快递",
			img: "https://bicpic.baikewang.com/images/1636616024011.png",
		},
		shentong: {
			name: "申通快递",
			img: "https://bicpic.baikewang.com/images/1636616024014.png",
		},
		shunfeng: {
			name: "顺丰速运",
			img: "https://bicpic.baikewang.com/images/1636616024009.png",
		},
		huitongkuaidi: {
			name: "百世快递",
			img: "https://bicpic.baikewang.com/images/1636616024005.png",
		},
		youzhengguonei: {
			name: "邮政快递包裹",
			img: "https://bicpic.baikewang.com/images/1636616024015.png",
		},
		ems: {
			name: "EMS",
			img: "https://bicpic.baikewang.com/images/1636616024015.png",
		},
		youzhengbk: {
			name: "邮政标准快递",
			img: "https://bicpic.baikewang.com/images/1636616024015.png",
		},
	};

	// 分享事件
	Vue.prototype.select = (e) => {
		let {
			item,
			index
		} = e;
		// item.name   wx
		switch (item.name) {
			case 'wx':
				shareWx();
				break;
			case 'wxcircle':
				shareWxcircle();
				break;
		}
	};
	Vue.prototype.toggleTips = (index, isOpenInfo) => {
		let obj = {
			'open': 'bottom',
			'bottom': 'open',
			'': 'open'
		}
		let str = obj[isOpenInfo[index]] || 'open';
		return str;
	};
	// 查看考试报告
	Vue.prototype.popupBtnClick = async function (e, info) {
		let that = this;
		if (e == '查看考试报告') {
			uni.setStorageSync('examReportInfo', info || {});
			that.applicationRewritingNavigateTo({
				url: '/pages/applicationDetail/comparisonTable/details'
			});
		}
	};
	// 返回上一页 - 报考数据
	Vue.prototype.$return = function(val = 1) {
		let pages = getCurrentPages(); //当前页
		let beforePage = pages[pages.length - 2]; //上个页面
		let flag = !!beforePage;
		if (flag) {
			uni.navigateBack({
				delta: val
			});
		} else {
			uni.redirectTo({
				url: '/application_data/pages/applicationPage/home'
			});
		}
	};
	// 随机生成指定位数字符
	Vue.prototype.randomString = () => {
		let len = 32;
		let chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz';
		let maxPos = chars.length;
		let character = '';
		for (let i = 0; i < len; i++) {
			character += chars.charAt(Math.floor(Math.random() * maxPos))
		}
		return character;
	};
	// base64转图片路径  解决canvas绘制不支持base64问题 兼容app，微信，h5
	Vue.prototype.base64ToPath = async (base64) => {
		return new Promise(function (resolve, reject) {
			if (typeof window === 'object' && 'document' in window) {
				base64 = base64.split(',');
				var type = base64[0].match(/:(.*?);/)[1];
				var str = atob(base64[1]);
				var n = str.length;
				var array = new Uint8Array(n);
				while (n--) {
					array[n] = str.charCodeAt(n);
				}
				return resolve((window.URL || window.webkitURL).createObjectURL(new Blob([
					array
				], {
					type: type
				})));
			}
			var extName = base64.match(/data\:\S+\/(\S+);/);
			if (extName) {
				extName = extName[1];
			} else {
				reject(new Error('base64 error'));
			}
			var fileName = Date.now() + '.' + extName;
			if (typeof plus === 'object') {
				var bitmap = new plus.nativeObj.Bitmap('bitmap' + Date.now());
				bitmap.loadBase64Data(
					base64,
					function () {
						var filePath = '_doc/uniapp_temp/' + fileName;
						bitmap.save(
							filePath, {},
							function () {
								bitmap.clear();
								resolve(filePath);
							},
							function (error) {
								bitmap.clear();
								reject(error);
							}
						);
					},
					function (error) {
						bitmap.clear();
						reject(error);
					}
				);
				return;
			}
			if (typeof wx === 'object' && wx.canIUse('getFileSystemManager')) {
				var filePath = wx.env.USER_DATA_PATH + '/' + fileName;
				wx.getFileSystemManager().writeFile({
					filePath: filePath,
					data: base64.replace(/^data:\S+\/\S+;base64,/, ''),
					encoding: 'base64',
					success: function () {
						resolve(filePath);
					},
					fail: function (error) {
						reject(error);
					}
				});
				return;
			}
			reject(new Error('not support'));
		});
	};
	Vue.prototype.pathToBase64 = async (path) => {
		return new Promise(function (resolve, reject) {
			if (typeof window === 'object' && 'document' in window) {
				if (typeof FileReader === 'function') {
					var xhr = new XMLHttpRequest()
					xhr.open('GET', path, true)
					xhr.responseType = 'blob'
					xhr.onload = function () {
						if (this.status === 200) {
							let fileReader = new FileReader()
							fileReader.onload = function (e) {
								resolve(e.target.result)
							}
							fileReader.onerror = reject
							fileReader.readAsDataURL(this.response)
						}
					}
					xhr.onerror = reject
					xhr.send()
					return
				}
				var canvas = document.createElement('canvas')
				var c2x = canvas.getContext('2d')
				var img = new Image
				img.onload = function () {
					canvas.width = img.width
					canvas.height = img.height
					c2x.drawImage(img, 0, 0)
					resolve(canvas.toDataURL())
					canvas.height = canvas.width = 0
				}
				img.onerror = reject
				img.src = path
				return
			}
			if (typeof plus === 'object') {
				let tempUrl = getLocalFilePath(path);
				plus.io.resolveLocalFileSystemURL(tempUrl, function (entry) {
					entry.file(function (file) {
						var fileReader = new plus.io.FileReader()
						fileReader.onload = function (data) {
							resolve(data.target.result)
						}
						fileReader.onerror = function (error) {
							reject(error)
						}
						fileReader.readAsDataURL(file)
					}, function (error) {
						reject(error)
					})
				}, function (error) {
					reject(error)
				})
				return
			}
			if (typeof wx === 'object' && wx.canIUse('getFileSystemManager')) {
				wx.getFileSystemManager().readFile({
					filePath: path,
					encoding: 'base64',
					success: function (res) {
						resolve('data:image/png;base64,' + res.data)
					},
					fail: function (error) {
						reject(error)
					}
				})
				return
			}
			reject(new Error('not support'))
		})
	};
	// 数组转字符串
	Vue.prototype.arrayToString = (arr, symbol = '、') => {

		return arr && arr.length ? arr.join(symbol) : ''
	};
	// 加载完成后默认显示指定的tooltips
	Vue.prototype.complete = (e, text, unit = '分', index = 0) => {
		uCharts.instance[e.id].showToolTip(
			// unit 需要显示的单位 不必填
			{
				changedTouches: [{
					x: 0,
					y: 100,
					unit: unit
				}]
			},
			// index  默认显示的tooltip下标
			{
				index: index
			}
		);
	};
	// 取数组中最接近指定值的指定位数
	Vue.prototype.getClosestTen = (arr, target, num = 10) => {
		let numbers = [];
		arr.forEach((item, index) => {
			numbers.push({
				index: index,
				number: Number(item)
			})
		})
		// 根据与目标值的差值进行排序
		let closestTen = numbers.sort((a, b) => Math.abs(a.number - target) - Math.abs(b.number - target));
		// sorted.forEach((item, index) => {
		// 	item.newIndex = index
		// })
		// 取前十个元素
		// let closestTen = sorted.slice(0, num);
		// closestTen = closestTen.sort((a, b) => {
		// 	return a.number - b.number;
		// })
		return closestTen;
	};
	// 微信授权
	// 获取微信用户信息
	Vue.prototype.getWxUserInfo = () => {
		let weixinOauth = null;
		plus.oauth.getServices(
			function (services) {
				for (let i in services) {
					let service = services[i];
					// 获取微信登录对象
					if (service.id == 'weixin') {
						weixinOauth = service;
						break;
					}
				}
				console.log(weixinOauth)
				// "userInfo": {
				// 	"openid": "oRrdQt1pECqHBMXODFlpIbmc1BF8",
				// 	"nickname": "。",
				// 	"sex": 0,
				// 	"language": "",
				// 	"city": "",
				// 	"province": "",
				// 	"country": "",
				// 	"headimgurl": "https://thirdwx.qlogo.cn/mmopen/vi_32/Q0j4TwGTfTKjGZ22yY9dqfVQQQS2fSZUMtHbkvG1iashhCFK8oUQ8icENRVcu5buSgXNiajZFvxicdzwyTtYhuQ4CA/132",
				// 	"privilege": [],
				// 	"unionid": "oU5YytzE617FXgdvl8sNJXpqbAys"
				// }
			},
			function (err) {
				// 获取 services 失败
			}
		);
	}

	// App一键登录
	Vue.prototype.appPhoneLogin = function () {
		let that = this;
		let isOpenLocalPhoneLogin = getApp().globalData && getApp().globalData.commonStaticInfo && !!getApp().globalData.commonStaticInfo.open_local_phone_login;
		// #ifdef APP-PLUS
		if (isOpenLocalPhoneLogin) {
			uni.showLoading({
				title: '',
				mask: true
			});
			uni.preLogin({
				provider: 'univerify',
				success(){  //预登录成功
					// 显示一键登录选项
					that.appLogin();
				},
				fail(res){  // 预登录失败
					// 不显示一键登录选项（或置灰）
				// 根据错误信息判断失败原因，如有需要可将错误提交给统计服务器
					console.log(res.errCode,'fail')
					console.log(res.errMsg,'fail')
					console.log(res)
					uni.hideLoading();
					uni.closeAuthView();
					uni.navigateTo({
						url: '/pages/loginWithVerCodeOrPass/passWordLogin/passWordLogin'
					});
				}
			})
			console.log('-----*-----**')
		} else {
			uni.hideLoading();
			uni.closeAuthView();
			uni.navigateTo({
				url: '/pages/loginWithVerCodeOrPass/passWordLogin/passWordLogin'
			});
		}

		// #endif
		// #ifndef APP-PLUS
		uni.navigateTo({
			url: '/pages/loginWithVerCodeOrPass/passWordLogin/passWordLogin'
		});
		// #endif

	}
	Vue.prototype.appLogin = function(){
		let that = this;
		uni.login({
			provider: 'univerify',
			univerifyStyle: {
				fullScreen: false, // 是否全屏显示，true表示全屏模式，false表示非全屏模式，默认值为false。
				backgroundColor: '#ffffff', // 授权页面背景颜色，默认值：#ffffff
				// backgroundImage: 'static/imgs/logo/ditu.png', // 全屏显示的背景图片，默认值："" （仅支持本地图片，只有全屏显示时支持）
				phoneNum: {
					fontSize: 22,
					color: '#202020' // 手机号文字颜色 默认值：#000000
				},
				slogan: {
					color: '#BBBBBB' //  slogan 字体颜色 默认值：#8a8b90
				},
				icon: {
					path: 'static/imgs/logo/head.png', // 自定义显示在授权框中的logo，仅支持本地图片 默认显示App logo
					width: '390px', //图标宽度 默认值：60px
					height: '60px' //图标高度 默认值：60px
				},
				// closeIcon: {
				// 	path: 'static/imgs/close.png',
				// 	width: '30px',
				// 	height: '30px'
				// },
				authButton: {
					normalColor: '#3479f5', // 授权按钮正常状态背景颜色 默认值：#3479f5
					highlightColor: '#2861c5', // 授权按钮按下状态背景颜色 默认值：#2861c5（仅ios支持）
					disabledColor: '#73aaf5', // 授权按钮不可点击时背景颜色 默认值：#73aaf5（仅ios支持）
					textColor: '#ffffff', // 授权按钮文字颜色 默认值：#ffffff
					borderRadius: '10px',
					title: '本机号码一键登录' // 授权按钮文案 默认值：“本机号码一键登录”
				},
				privacyTerms: {
					defaultCheckBoxState: false, // 条款勾选框初始状态 默认值： true
					isCenterHint: false,
					uncheckedImage: 'static/imgs/logo/default.png', // 可选 条款勾选框未选中状态图片（仅支持本地图片 建议尺寸 24x24px）(3.2.0+ 版本支持)
					checkedImage: 'static/imgs/logo/check.png', // 可选 条款勾选框选中状态图片（仅支持本地图片 建议尺寸24x24px）(3.2.0+ 版本支持)
					checkBoxSize: 12, // 可选 条款勾选框大小，仅android支持
					textColor: '#858688', // 文字颜色 默认值：#BBBBBB
					termsColor: '#121317', //  协议文字颜色 默认值： #5496E3
					prefix: '我已阅读并同意', // 条款前的文案 默认值：“我已阅读并同意”
					suffix: '并使用本机号码登录', // 条款后的文案 默认值：“并使用本机号码登录”
					privacyItems: [
						// 自定义协议条款，最大支持2个，需要同时设置url和title. 否则不生效
						{
							url: 'https://gov-info.baikelive.com/agreement/userAgreement.html', // 点击跳转的协议详情页面
							title: '用户协议' // 协议名称
						},
						{
							url: 'https://gov-info.baikelive.com/agreement/privacyAgreement.html', // 点击跳转的协议详情页面
							title: '隐私政策' // 协议名称
						}
					]
				},
				otherLoginButton: {
					visible: true, // 是否显示其他登录按钮，默认值：true
					normalColor: '', // 其他登录按钮正常状态背景颜色 默认值：透明
					highlightColor: '', // 其他登录按钮按下状态背景颜色 默认值：透明
					textColor: '#121317', // 其他登录按钮文字颜色 默认值：#656565
					title: '验证码或密码登录', // 其他登录方式按钮文字 默认值：“其他登录方式”
					borderColor: '', //边框颜色 默认值：透明（仅iOS支持）
					borderRadius: '0px' // 其他登录按钮圆角 默认值："24px" （按钮高度的一半）
				}
			},
			success: async (res) => {
				uni.hideLoading();
		console.log('-----*-123----**')
				const authResult = res.authResult;
				let info = {
					type: 'uniapp',
					code: authResult.access_token,
					encrypted_data: authResult.openid,
				}
				await that.loginWeCom(info);
				// uni.closeAuthView(); //关闭一键登录弹出窗口
			},
			fail(res) {
				uni.hideLoading();
		console.log('-----*-456----**',res)
				if (res.code == 30003) {
					// 关闭页面
					uni.closeAuthView();
				} else {
					uni.navigateTo({
						url: '/pages/loginWithVerCodeOrPass/passWordLogin/passWordLogin'
					});
					// 其他登录方式
					console.log('失败,其他登录方式');
					uni.closeAuthView();
				}
			}
		});
	}


	// 微信授权登录
	Vue.prototype.weixinLoginForApp = () => {
		return new Promise((resolve, reject) => {
			uni.login({
				provider: 'weixin',
				"onlyAuthorize": true, // 微信登录仅请求授权认证
				success: function (loginRes) {
					const {
						code
					} = loginRes;
					resolve(code)
				},

				fail: function (res) {
					reject(res)
				}
			});
		});

	}

	// 账户登录接口
	Vue.prototype.loginWeCom = async function (info) {
		let that = this;
		if (!info) return false;
		/**
		 * type  可选值：'uniapp', 'weixin', 'apple', 'password', 'code'
		 * code,
		 * encrypted_data,
		 * iv,
		 * invite_id
		 *
		 */
		uni.showLoading({
			title: '正在登录~',
			mask: true
		});
		let {
			code,
			data
		} = await that.$api.login(info);

		if (code != 0) { uni.hideLoading(); return false; }
		if (!data) return false;
		uni.setStorageSync('token', data);
		getApp().globalData.token = data;
		that.$store.commit('changeIsShow', false);
		await that.setSelfInfo();
		getApp().getSysUserInfo();
		uni.hideLoading();
		uni.closeAuthView();
		return data || true;
	}
	// 存储指引页信息
	Vue.prototype.setSelfInfo = async function () {
		let that = this;
		let stepInfo = uni.getStorageSync('stepInfo') || {};
		let provinceInfo = uni.getStorageSync('provinceInfo')||{};
		let info = {
			purpose_major: stepInfo.major ? stepInfo.major.major_id : '',
			edu_system_id: stepInfo.year ? stepInfo.year.activeChildren.edu_system_id : '',
			province_id: provinceInfo.province_id || (stepInfo.province ? stepInfo.province.province_id : '')
		}
		let { code, data } = await that.$api.editSelfInfo(info);
		if (code != 0) return;
		await that.getSelfInfo();
		uni.setStorageSync('stepInfo', { isClose: true })

	}
	// 发送验证码
	Vue.prototype.sendCode = async function (info) {
		let that = this;
		if (!info) return false;
		uni.showLoading({
			title: '获取验证码~',
			mask: true
		});
		let {
			code,
			data
		} = await that.$api.sendPhoneCode(info);
		uni.hideLoading();
		if (code != 0) return false;
		return data || true;
	}

	// 返回页面

	Vue.prototype.appReturn = () => {
		let pages = getCurrentPages(); // 获取当前页面栈的实例
		let currPage = pages[pages.length - 1]; //当前页面
		let prevPage = pages[pages.length - 2]; //上一个页面
		if (!prevPage) {
			uni.switchTab({
				url: '/pages/tabbarPages/home/home'
			});
		} else {
			uni.navigateBack({
				delta: 1 //返回层数，2则上上页
			});
		}
	}

	// 格式化显示是手机号
	Vue.prototype.formatPhoneNumber = function (phoneNumber) {
		// 去除所有非数字字符
		const numberOnly = String(phoneNumber).replace(/\D/g, '');
		// 判断手机号码长度
		if (numberOnly.length === 11) {
			// 使用正则表达式将手机号码分成三位、四位和四位进行格式化
			return numberOnly.replace(/(\d{3})(\d{4})(\d{4})/, '$1 $2 $3');
		} else {
			// 不符合手机号码长度，直接返回原始值
			return phoneNumber;
		}
	}

	// 随机英文
	Vue.prototype.randomString = (e) => {
		let num = e || 32;
		let t = "abcdefhijkmnprstwxyz";
		let a = t.length;
		let n = "";
		for (let i = 0; i < num; i++) n += t.charAt(Math.floor(Math.random() * a));
		return n
	}



}

const shareWx = (share_url) => {
	uni.share({
		provider: 'weixin',
		scene: 'WXSceneSession',
		type: 2,
		// href: share_url,
		title: '拜课网',
		// summary: this.goods.description,
		imageUrl: `https://bicpic.baikewang.com/images/1654479372581.png`,
		fail(err) {
			uni.showToast({
				title: err.errMsg,
				icon: 'none'
			})
		}
	})
}
const shareWxcircle = (share_url) => {
	uni.share({
		provider: 'weixin',
		scene: 'WXSceneTimeline',
		type: 0,
		href: share_url,
		summary: this.goods.description,
		imageUrl: this.goods.pictures[0],
		fail(err) {
			uni.showToast({
				title: err.errMsg,
				icon: 'none'
			})
		}
	})
}
export default install